﻿@page
@model GZipTestModel
@{
    ViewData["Title"] = "GZip测试";
}
<h1>@ViewData["Title"]</h1>
<label for="input">原字符串：</label>
<br />
<textarea id="input" name="input" type="text" rows=3 cols=100>这是压缩测试字符串，abcd EFGH 1234 !@@#$ %^&* _+-=</textarea>
<br />
<label for="compressedOutput">压缩后：</label>
<br />
<textarea id="compressedOutput" name="compressedOutput" type="text" rows=3 cols=100></textarea>
<br />
<label for="uncompressedOutput">解压后：</label>
<br />
<textarea id="uncompressedOutput" name="uncompressedOutput" type="text" rows=3 cols=100></textarea>
<br />
<input type="checkbox" id="useBase64" name="useBase64" checked="checked" style="padding: 10px 0" />
<label for="useBase64">使用Base64编码</label>
<br />
<input id="frontendTest" type="button" value="前端压缩/前端解压" />
<input id="backendTest" type="button" value="前端压缩/后端解压" onclick="uploadData()" />

@section Scripts {
    <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/jsencrypt/3.3.2/jsencrypt.min.js"></script>
    <!-- 引入pako的CDN链接 -->
    @* <script src="https://cdnjs.cloudflare.com/ajax/libs/pako/2.1.0/pako.min.js"></script> *@
    <script src="/js/pako.min.js"></script>
    <script type="text/javascript">
        // 压缩
        function compressString(inputStr) {  
           // 将字符串转换为 Uint8Array
            const uint8Array = new TextEncoder().encode(inputStr);
            // 使用 pako.gzip 压缩
            const compressed = pako.gzip(uint8Array);  
            return new Uint8Array(compressed);  
        }

        // 解压
        function decompressString(compressed) {  
            const uint8Array = new Uint8Array(compressed);
            // 使用 pako.inflate 解压（注意：gzip 压缩的数据应使用 inflate 解压）
            const decompressed = pako.inflate(uint8Array);
            // 将解压后的 Uint8Array 转换回字符串
            return new TextDecoder().decode(decompressed);
        }

        // 压缩为Base64
        function compressToBase64(inputStr) {
            // 将字符串转换为 Uint8Array
            const uint8Array = new TextEncoder().encode(inputStr);
            // 使用 pako.gzip 压缩
            const compressed = pako.gzip(uint8Array);
            // 将 Uint8Array 转换为 Base64 字符串
            return btoa(new Uint8Array(compressed).reduce((data, byte) => data + String.fromCharCode(byte), ''));
        }

        // 从Base64解压
        function decompressFromBase64(base64Str) {
            // 将 Base64 字符串解码为 Uint8Array
            const compressed = atob(base64Str).split('').map(char => char.charCodeAt(0));
            const uint8Array = new Uint8Array(compressed);
            // 使用 pako.inflate 解压（注意：gzip 压缩的数据应使用 inflate 解压）
            const decompressed = pako.inflate(uint8Array);
            // 将解压后的 Uint8Array 转换回字符串
            return new TextDecoder().decode(decompressed);
        }

        // 前端压缩/前端解压
        $('#frontendTest').click(function () {
            var useBase64 = $('#useBase64').prop('checked');
            console.log('使用Base64编码: ', useBase64);

            $('#compressedOutput').val('');
            $('#uncompressedOutput').val('');
            
            // 压缩
            var compressed;
            if(useBase64){
                compressed = compressToBase64($('#input').val());
            } 
            else {
                compressed = compressString($('#input').val());
            }
            console.log("前端压缩: " + compressed);
            $('#compressedOutput').val(compressed);

            // 解压
            var uncompressed;
            if(useBase64){
                uncompressed = decompressFromBase64(compressed);
            }
            else {
                uncompressed = decompressString(compressed);
            }
            console.log("前端解压: " + uncompressed);
            $('#uncompressedOutput').val(uncompressed);

            // 原字符串 是否和 解压后字符串 相等
            if (uncompressed == $('#input').val()) {
                console.log('压缩、解压成功！');
            }
            else {
                console.log('压缩、解压失败');
                alert('压缩、解压失败！');
            }
        });

        async function uploadData() {
            const dataToCompress = $('#input').val();
            console.log("原字符串: " + dataToCompress);
            const compressedData = compressString(dataToCompress);
            console.log("前端压缩: " + compressedData);
            $('#compressedOutput').val(compressedData);

            const formData = new FormData();
            formData.append('businessType', 'businessType数据');
            formData.append('blobData', new Blob([compressedData], { type: 'application/octet-stream' }));
            try {
                const response = await fetch('/api/Upload/UploadCompressedData', {
                    method: 'POST',
                    body: formData
                    // 注意：不要设置Content-Type头，因为FormData会自动设置
                });

                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }

                const data = await response.json();
                console.log(data);
                console.log("后端解压: " + data.content);
                $('#uncompressedOutput').val(data.content);

                // 原字符串 是否和 解压后字符串 相等
                if (data.content == $('#input').val()) {
                    console.log('压缩、解压成功！');
                }
                else {
                    console.log('压缩、解压失败');
                    alert('压缩、解压失败！');
                }

            } catch (error) {
                console.error('There was a problem with your fetch operation:', error);
                alert('Failed to upload.');
            }
        }

    </script>
}
